package com.cloudkinto.session;

import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.entity.CompanyDo;
import com.cloudkinto.entity.UserDo;
import com.cloudkinto.service.company.CompanyService;
import com.cloudkinto.service.user.UserService;
import com.cloudkinto.service.warehouse.WarehouseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.UUID;

@Transactional(rollbackFor = Exception.class)//事务回滚
@Service
public class UserSessionManagerImpl implements UserSessionManager {

    private static Logger logger = LoggerFactory.getLogger(UserSessionManagerImpl.class);

    @Resource
    private UserService userService;
    @Resource
    private WarehouseService warehouseService;
    @Resource
    private CompanyService companyService;
    @Resource
    private UserSessionRepository userSessionRepository;

    @Override
    public UserSession getSession(String sessionId) {
        return userSessionRepository.querySession(sessionId);
    }

    @Override
    public UserSession getSession(HttpServletRequest request) throws UserSessionException {
        String sessionId = request.getHeader(UserSession.SESSION_ID_KEY);
        UserSession userSession = userSessionRepository.querySession(sessionId);
        if (userSession == null) {
            // 会话失效
            request.getSession().removeAttribute(UserSession.SESSION_ID_KEY);
            throw new UserSessionException("用户会话不存在，或已过期，请重新登陆");
        }
        return userSession;
    }

    public UserSession keepAlive(HttpServletRequest request) throws UserSessionException {
        Object obj = request.getSession().getAttribute(UserSession.SESSION_ID_KEY);
        if (obj != null) {
            UserSession session = UserSession.class.cast(obj);
            userSessionRepository.saveSession(session);
            return session;
        }
        return null;
    }

    @Override
    public void saveSession(UserSession session) {
        userSessionRepository.saveSession(session);
    }

    @Override
    public UserSession createSession(UserDo userDo, String source) throws UserSessionException {
        //判断 不能用前台的token 请求后台api
        if (!Objects.equals(StaticDict.System_RoleType.getRoleType(source), userDo.getUserType())) {
            throw new UserSessionException(SysConstant.NoPower);
        }
        UserSession session = new UserSession();
        try {
            session.setSessionId(UUID.randomUUID().toString());
            session.setUserId(userDo.getId());
            session.setCompanyId(userDo.getCompanyId());
            session.setTenantId(userDo.getTenantId());
            session.setUsername(userDo.getUserName());
            session.setUserAccount(userDo.getUserAccount());
            session.setUserType(userDo.getUserType());
            if ("oms".equals(source)) {
                session.setCompanyId(userDo.getCompanyId());
                CompanyDo companyDo = companyService.getById(userDo.getCompanyId());
                if (companyDo != null) {
                    session.setCompanyCode(companyDo.getCompanyCode());
                    session.setCompanyName(companyDo.getCompanyName());
                }
            } else if ("omp".equals(source)||"api".equals(source)) {
                session.setTenantId(userDo.getTenantId());
                session.setStorageId(warehouseService.getLastWhId(source, userDo.getId(), userDo.getTenantId()));
            }
            userSessionRepository.saveSession(session);
            return session;
        } catch (Exception ex) {
            throw new UserSessionException("指定用户不存在，无法创建会话");
        }
    }


    @Override
    public void clearSession(String sessionId) {
        userSessionRepository.removeSession(sessionId);
    }
}
